<?php

namespace App\Console\Commands;

use App\Models\Order;
use App\Models\OrderLease;
use App\Models\OtherWithholdLog;
use App\Services\AlipayService;
use App\Services\EsignService;
use App\Services\OrderService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class needPayOrderLeaseCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'needPayOrderLease';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '易付宝需要扣款的分期账单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    protected function handleExec()
    {
       $this->needPayOrderLease();
    }

    const TIME_LIMIT = 3; //单位小时
    const ORDER_NUM_LIMIT = 50; //一次操作订单数量
    const NOT_HANDEL_SHOP = [

    ];

    /**
     * 签约未支付订单分期账单到期易付宝扣款付款
     */
    public function needPayOrderLease(){
        try {

            $leaseStatus = [
                OrderLease::ORDER_LEASE_STATUS_NOPAY,
                OrderLease::ORDER_LEASE_STATUS_OVERDUE,
            ];
            $where = [
                ['o.pay_type','!=',Order::ORDER_PAY_TYPE_HUABEI],
                ['ol.withhold_status',OrderLease::LEASE_WITHHOLD_STATUS_NO],
                ['ol.begin_time','<=',strtotime(date('Y-m-d 23:59:59',strtotime('-1 day')))],
                ['m.openId','!=',''],
            ];
            //数据
            $data = Order::from('sp_order_2 as o')
                ->select('o.id','o.status as order_status','ol.id as lease_id','ol.begin_time','ol.status as lease_status')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id','ol.order_id')
                ->leftjoin('se_member_2 as m', 'o.uid','m.id')
                ->whereIn('o.status',OrderService::getOrderStatus(OrderService::ORDER_OVERDUE_COUNT))
                ->whereIn('ol.status',$leaseStatus)
                ->where($where)
                ->limit(self::ORDER_NUM_LIMIT)
                ->orderBy('ol.id', 'asc')
                ->get();
            $data = obToArray($data);
            if($data){
                Redis::set('needPayOrderlease',json_encode($data));
//                foreach ($data as $k=>$v){
//                    $overDay = floor((strtotime(date('Y-m-d H:i:s')) - $v['begin_time']) / 86400);
//                }


            $this->infoLog('易付宝需要扣款的分期账单执行成功',$data);
            }
        }catch (\Exception $exception){
            $this->infoLog('易付宝需要扣款的分期账单执行失败'.$exception->getMessage());
        }
    }
}
